<template>

    <el-card class="box-card">
        <template #header>
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <span>基本信息</span>
                <el-button v-if="$store.state.user.is_teacher" type="primary" round
                    @click="handleEditCourse">编辑</el-button>

            </div>
        </template>
        <el-descriptions size="large" border :column="2">
            <el-descriptions-item v-for="item in filteredCourseInfo" :key="item.label">
                <template #label>
                    {{ item.label }}
                </template>
                {{ item.value }}
            </el-descriptions-item>
        </el-descriptions>
        <el-descriptions style="max-width: 100%;" size="large" border>
            <el-descriptions-item >
                <template #label>
                    课程描述
                </template>
                {{ courseInfo.description }}
            </el-descriptions-item>
        </el-descriptions>
    </el-card>
    <!-- <div style="width: 100%;text-align: left;">
        <h2>基本信息</h2>
    </div> -->

    <el-card v-if="$store.state.user.is_teacher" class="box-card" >
        <template #header>
            <div class="card-header">
                <span>结课时间</span>
            </div>
        </template>
        <div class="box" style="margin:10px">
            <div class="item">

                <el-date-picker type="datetime" placeholder="选择结课时间" size="default" clearable v-model="tempEndTime"
                    @change="handleEndTimeChange" />
                <el-button style="margin-left: 10px;" type="primary" v-if="showSaveButton"
                    @click="handleEndTimeSave">保存</el-button>
                <el-button v-if="showSaveButton" @click="handleEndTimeCancel">取消</el-button>
                <p style="color:#888;font-size:12px;margin-left: auto;">若不填写结课时间，则永不结束</p>
            </div>
            <div v-if="$store.state.user.is_teacher" class="item">
                <el-button type="danger" @click="handleDeleteCourse">删除班课</el-button>
                <el-button @click="handleChangeCourseStatue('finished')" v-if="courseInfo.status === 'ongoing'"
                    type="primary">结束班课</el-button>

                <el-button @click="handleChangeCourseStatue('ongoing')" v-if="courseInfo.status === 'finished'"
                    type="primary">启动班课</el-button>
            </div>


        </div>
    </el-card>
    <el-card class="box-card" v-else>
        <template #header>
            <div class="card-header">
                <span>班级操作</span>
            </div>
        </template>
        <div class="box">
            <div v-if="!$store.state.user.is_teacher" class="item">
                <el-button type="danger" @click="handleExitCourse">退出班课</el-button>
            </div>
        </div>
    </el-card>
</template>


<script lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, onMounted, watch } from 'vue'
import { deleteCourseApi, changeCourseStatusApi, changeCourseEndTimeApi } from '@/api/course';
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { exitCourseApi } from '@/api/course'
interface CourseInfo {
    title: string;
    course_id: string;
    term: string;
    create_time: string;
    update_time: string;
    start_time: string;
    end_time: string;
    stu_counts: number;
    description: string;
    teachingCourseName: string;
    status: string;
    cover: string;
    homework_weight: number;
    experiment_weight: number;
    exam_weight: number;
}

export default {

    props: {
        courseInfo: Object as () => CourseInfo

    },
    computed: {
        filteredCourseInfo(): { label: string; value: string }[] {
            const labels: Record<keyof CourseInfo, string> = {

                title: '班课名', stu_counts: '总人数',
                course_id: '班课号', homework_weight: '作业权重',
                teachingCourseName: '授课课程', experiment_weight: '实验权重',
                term: '开课学期', exam_weight: '考试权重',
                end_time: '结束时间', 
            };

            return Object.entries(labels).map(([key, label]) => ({ label, value: this.courseInfo[key as keyof CourseInfo] }));
        }
    },

    setup(props, { emit }) {

        const store = useStore()
        const router = useRouter()
        const tempEndTime = ref(null) // 临时存储的结课时间
        const showSaveButton = ref(false) // 是否显示保存按钮
        const isEditting = ref(false) // 是否处于编辑状态

        const handleEditCourse = () => {
            isEditting.value = true;

            // 跳转到编辑页面
            router.push({
                name: 'editCourse',
                state: {
                    course_id: props.courseInfo.course_id,
                    user_id: store.state.user.user_id,
                    cover: props.courseInfo.cover,
                    title: props.courseInfo.title,
                    term: props.courseInfo.term,
                    description: props.courseInfo.description,
                    start_time: props.courseInfo.start_time,
                    end_time: props.courseInfo.end_time,
                    status: props.courseInfo.status,
                    teachingCourseName: props.courseInfo.teachingCourseName,
                    homework_weight: props.courseInfo.homework_weight,
                    exam_weight: props.courseInfo.exam_weight,
                    experiment_weight: props.courseInfo.experiment_weight,
                }
            })
        };
        const handleChangeCourseStatue = (status: string) => {
            changeCourseStatusApi({
                status: status,
                course_id: props.courseInfo.course_id,
                user_id: store.state.user.user_id
            }).then((response: any) => {
                if (response.code === 200) {
                    ElMessage.success('改变班课状态成功');
                    location.reload();
                }
                else ElMessage.error(response.msg)
            }).catch((error) => {
                ElMessage.error('修改班课状态失败')
            })
        };
        const handleEndTimeChange = (value: any) => {
            // 结课时间改变时更新临时变量
            tempEndTime.value = value;
            showSaveButton.value = true; // 显示保存按钮
        };
        const handleEndTimeSave = () => {
            // 保存操作
            changeCourseEndTimeApi({
                course_id: props.courseInfo.course_id,
                user_id: store.state.user.user_id,
                end_time: tempEndTime.value
            }).then((response: any) => {
                if (response.code === 200) {
                    ElMessage.success('结课时间保存成功')
                    location.reload();
                }
                else ElMessage.error(response.msg)
            }).catch((error) => {
                ElMessage.error('结课时间保存失败')
            })

            ElMessage.success('保存成功');
            showSaveButton.value = false; // 隐藏保存按钮
        };
        const handleEndTimeCancel = () => {
            // 取消操作，还原结课时间
            tempEndTime.value = props.courseInfo.end_time;
            // ElMessage.success('取消成功');
            showSaveButton.value = false; // 隐藏保存3按钮
        };

        const handleDeleteCourse = () => {
            ElMessageBox.prompt('输入班课号以删除课程', '删除课程', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning',
                confirmButtonClass: 'el-button--danger',
                // inputPattern: /^\d{6}$/, // 此处假设班课号是6位数字
                inputErrorMessage: '输入错误', // 验证失败时的错误提示
            })
                .then(({ value }) => {

                    // 此处处理用户点击确定后的逻辑
                    if (String(value) === String(props.courseInfo.course_id)) { // 假设班课号为123456
                        deleteCourseApi({
                            course_id: props.courseInfo.course_id,
                            user_id: store.state.user.user_id
                        }).then((response: any) => {
                            if (response.code === 200) {
                                ElMessage.success('班课删除成功')
                                router.replace({ path: '/teacher/home', state: { reload: true } })

                            }
                            else ElMessage.error(response.msg)
                        }).catch((error) => {
                            ElMessage.error('班课删除失败')
                        })
                    } else {
                        ElMessage.error('班课号错误，删除失败')
                    }
                })
                .catch((error) => {

                    // 此处处理用户点击取消后的逻辑
                    ElMessage({
                        type: 'info',
                        message: '取消删除班课',
                    })
                })

        };
        const handleExitCourse = () => {
            ElMessageBox.confirm('是否退出班课？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                confirmButtonClass: 'el-button--danger',
            }).then(() => {
                // 此处处理用户点击确定后的逻辑
                exitCourseApi({
                    is_teacher: store.state.user.is_teacher,
                    course_id: props.courseInfo.course_id,
                    user_id: store.state.user.user_id
                }).then((response: any) => {
                    if (response.code === 200) {
                        ElMessage.success('退出班课成功')
                        if (store.state.user.is_teacher) {
                            // 跳转到首页，并且手动刷新首页，因为首页有缓存
                            router.replace('/teacher/home')
                        }
                        else {
                            router.replace('/student/home')
                        }
                    }
                    else ElMessage.error(response.msg)
                }).catch((error) => {
                    ElMessage.error('退出班课失败')
                })
            })
                .catch(() => {

                    // 此处处理用户点击取消后的逻辑
                    ElMessage({
                        type: 'info',
                        message: '取消退出班课',
                    })
                })

        };
        onMounted(() => {
            watch(() => props.propValue, (newValue, oldValue) => {
                tempEndTime.value = newValue.end_time; // 同步结课时间

            });
        })

        return {
            handleChangeCourseStatue,
            handleDeleteCourse,
            showSaveButton,
            handleEndTimeChange,
            handleEndTimeSave,
            handleEndTimeCancel,
            handleExitCourse,
            handleEditCourse,
            tempEndTime,
        };
    }

};
</script>

<style lang="scss" scoped>
.class-details {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}

.box-card {
    margin-top: 10px;

    .card-header {
        text-align: left;
    }

    .box {


        .item {
            display: flex;
            align-items: center;

            * {
                margin-right: 20px;
            }
        }
    }
}

.creator-info,
.members,
.course-info {
    margin-top: 20px;
}
</style>